<script setup lang="ts">
import TableView from '@/components/TableView.vue'
import {
  NButton,
  NSelect,
  NInput,
  NDataTable,
  NForm,
  NFormItem,
  NPagination,
  useMessage,
  type DataTableColumns,
  NSpace,
  NModal,
  NDatePicker,
  useDialog,
  NGrid,
  NGridItem
} from 'naive-ui'
import { h, onMounted, reactive, watch, ref } from 'vue'
import { sendRequest } from '@/utils/api'
import type { HttpResponsePagination, HttpResponse } from '@/utils/http'
import type { InterpreterModel } from '@/api/interpreter'
import { useRouter, useRoute } from 'vue-router'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import dayjs from 'dayjs'
import { RecordType } from '@/router/utils'

const message = useMessage()
const router = useRouter()
const route = useRoute()

const modalVisible = ref<boolean>(false)
const revokeId = ref<string | null>(null)

const paginationReactive = reactive({
  date: null,
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})

const formInfo: any = reactive({
  conferenceRoomId: null,
  fromStatusCode: null,
  content: null,
  startTime: null,
  endTime: null
})

const statusList = [
  { label: '撤回', value: 'A0602' },
  { label: '审批中', value: 'A0603' },
  { label: '拒绝', value: 'A0604' },
  { label: '通过', value: 'A0605' }
]

const tableData = ref<InterpreterModel[]>([])
const tableLoading = ref(false)
const queryTableData = async (flush = false) => {
  if (flush) paginationReactive.page = 1
  try {
    tableLoading.value = true
    const [error, res] = await sendRequest<HttpResponsePagination<InterpreterModel>>({
      module: 'digitalCollect',
      api: 'list',
      override: {
        params: {
          limit: paginationReactive.pageSize,
          page: paginationReactive.page,
          startUsageTime: paginationReactive.date
            ? dayjs(paginationReactive.date[0]).format('YYYY-MM-DD')
            : null,
          endUsageTime: paginationReactive.date
            ? dayjs(paginationReactive.date[1]).format('YYYY-MM-DD')
            : null
        }
      }
    })
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    tableData.value = res.data.list.map((r: any) => {
      return {
        ...r,
        exportLoading: false
      }
    })
    paginationReactive.itemCount = res.data.totalCount
  } catch (error) {
    console.log(error)
  } finally {
    tableLoading.value = false
  }
}
// 撤回消息
const revoke = async () => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'receiveOrDispatch',
    api: 'dispatchRevoke',
    override: {
      data: {
        functionCode: 'A0576',
        resourceId: revokeId.value
      }
    }
  })
  if (error) return message.error('撤回失败'), (modalVisible.value = false)
  if (res.code !== 0) return message.error('撤回失败'), (modalVisible.value = false)
  message.success('撤回成功')
  modalVisible.value = false
  queryTableData()
}
// 单条记录导出
const exportSingle = async (id: string) => {
  tableData.value.forEach((t: any) => {
    t.exportLoading = t.id === id
  })
  const [error, data, headers] = await sendRequest<HttpResponse>({
    module: 'digitalCollect',
    api: 'exportSingle',
    uri: {
      id
    }
  })
  if (error) {
    tableData.value.forEach((t: any) => {
      t.exportLoading = false
    })
    message.error('导出出错')
    throw new Error('导出出错')
  }
  tableData.value.forEach((t: any) => {
    t.exportLoading = false
  })
  download(headers, data, '杭州国家版本馆数字版本提用申请单')
  message.success('导出成功')
}
//导出
function download(headers: any, data: any, name?: string) {
  const val = headers['content-disposition']?.match(/(?<=filename=)(.*)/)
  let filename = val ? decodeURIComponent(val[0]) : name + '导出.xlsx'
  if (!filename.includes('xlsx')) {
    filename = filename.replace('xls', 'xlsx')
  }
  const a = document.createElement('a')
  let binaryData = []
  binaryData.push(data)
  a.href = window.URL.createObjectURL(new Blob(binaryData))
  a.download = filename
  a.click()
  window.URL.revokeObjectURL(a.href)
}

const columns: DataTableColumns<InterpreterModel> = [
  {
    title: '用户',
    key: 'userName',
    align: 'center'
  },
  {
    title: '部门',
    key: 'deptName',
    align: 'center'
  },
  {
    title: '使用时间',
    key: 'date',
    align: 'center',
    render: (row: any, index: number) => {
      if (!row.startUsageTime) {
        return ''
      }
      return `${row.startUsageTime.split(' ')[0]} 至 ${row.endUsageTime.split(' ')[0]}`
    }
  },
  {
    title: '用途',
    key: 'purpose',
    align: 'center'
  },
  {
    title: '提用版本名称',
    key: 'purpose',
    align: 'center'
  },
  {
    title: '申请时间',
    key: 'createTime',
    align: 'center'
  },
  {
    title: '审批状态',
    key: 'fromStatusCodeValue',
    align: 'center'
  },
  {
    title: '操作',
    key: 'operation',
    align: 'center',
    render: (row: any, index) => [
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => {
            RecordType.setRouteNameTypeFalse('A0576')
            router.push({ path: '/OA/DigitalCollation/MyWithdrawalDetail', query: { id: row.id } })
          }
        },
        {
          default: () => '详情'
        }
      ),
      row.fromStatusCode === 'A0605' &&
        h(
          NButton,
          {
            type: 'primary',
            quaternary: true,
            loading: row.exportLoading || false,
            onClick: () => {
              exportSingle(String(row.id))
            }
          },
          {
            default: () => '导出'
          }
        )
      // row.fromStatusCode === 'A0603' &&
      //   h(
      //     NButton,
      //     {
      //       type: 'primary',
      //       quaternary: true,
      //       onClick: () => {
      //         revokeId.value = String(row.id)
      //         modalVisible.value = true
      //       }
      //     },
      //     {
      //       default: () => '撤回'
      //     }
      //   ),
      // h(
      //   NButton,
      //   {
      //     type: 'primary',
      //     quaternary: true,
      //     onClick: () => {
      //       router.push({
      //         path: '/OA/digitalCollect/edit',
      //         query: { id: row.id as never, flat: true as never, flag: true as never }
      //       })
      //     }
      //   },
      //   {
      //     default: () => '再次发起'
      //   }
      // )
    ]
  }
]

watch(
  () => route,
  async () => {
    if (route.path == '/OA/DigitalCollation/MyWithdrawals') {
      queryTableData(true)
    }
  },
  { deep: true, immediate: true }
)
</script>

<template>
  <TableView class="table">
    <template #form>
      <div class="select-container">
        <div class="select-list">
          <NForm
            :show-feedback="false"
            label-placement="left"
            inline
          >
            <n-grid
              :cols="4"
              :x-gap="30"
              :y-gap="30"
            >
              <n-grid-item>
                <NFormItem label="用户：">
                  <NInput
                    v-model:value="formInfo.username"
                    clearable
                  />
                </NFormItem>
              </n-grid-item>
              <n-grid-item>
                <NFormItem label="部门：">
                  <NInput
                    v-model:value="formInfo.key2"
                    clearable
                  />
                </NFormItem>
              </n-grid-item>
              <n-grid-item>
                <NFormItem label="使用时间：">
                  <n-date-picker
                    v-model:value="formInfo.key3"
                    type="daterange"
                    clearable
                  />
                </NFormItem>
              </n-grid-item>
              <n-grid-item>
                <NFormItem label="提用版本名称：">
                  <NInput
                    v-model:value="formInfo.key4"
                    clearable
                  />
                </NFormItem>
              </n-grid-item>
              <n-grid-item>
                <NFormItem label="申请时间：">
                  <n-date-picker
                    v-model:value="formInfo.key5"
                    type="datetimerange"
                    clearable
                  />
                </NFormItem>
              </n-grid-item>
              <n-grid-item>
                <NFormItem label="审核状态:">
                  <NSelect
                    v-model:value="formInfo.fromStatusCode"
                    :options="statusList"
                    style="width: 150px"
                    clearable
                  />
                </NFormItem>
              </n-grid-item>
            </n-grid>
          </NForm>
        </div>
        <div class="select-line"></div>
        <div class="select-btns">
          <NButton
            type="primary"
            style="width: 78px; margin-right: 20rem"
            @click="queryTableData(true)"
          >
            查询
          </NButton>
          <NButton
            type="primary"
            ghost
            style="width: 78px"
            @click="() => {}"
          >
            重置
          </NButton>
        </div>
      </div>
    </template>
    <template #operate>
      <div class="operate-container">
        <NButton
          type="primary"
          @click="$router.push({ path: '/OA/DigitalCollation/MyWithdrawalAdd' })"
        >
          数字藏品提用
        </NButton>
      </div>
    </template>
    <template #table="props">
      <NDataTable
        v-bind="props"
        :columns="columns"
        :data="tableData"
        :pagination="false"
        :bordered="false"
        flex-height
        style="height: 100%"
      />
    </template>
    <template #pagination>
      <NPagination
        :page-sizes="paginationReactive.pageSizes"
        :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page"
        :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange"
        @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker
        show-quick-jumper
        :suffix="() => '页'"
      >
        <template #prefix>
          <span style="font-size: 14px">共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>

  <NModal
    :auto-focus="false"
    v-model:show="modalVisible"
    @close="modalVisible = false"
  >
    <VDialogContent
      @close="modalVisible = false"
      @submit="revoke"
      title="撤回提示"
    >
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定撤回吗？
      </div>
    </VDialogContent>
  </NModal>
</template>

<style scoped lang="scss">
.select-container {
  display: flex;
  align-items: center;
  //   gap: 19px;
  .select-line,
  .select-btns {
    margin-top: -20px;
  }
  .select-line {
    width: 84px;
    height: 1px;
    transform: rotate(90deg);
    background: #f1f2f4;
  }
  .select-btns {
    display: flex;
    flex-direction: column;
    gap: 20px;
  }
}
.table {
  height: 100%;
  padding: 29px 30px 42px;
  .operate-container {
    display: flex;
    gap: 20px;
    margin: 10px 0;
  }
}
// .interpreter_record_container {
//   height: 100%;
//   padding: 30rem;

//   .interpreter_record_form {
//     height: 7%;
//   }

//   .interpreter_record_table {
//     height: 87%;
//   }

//   .interpreter_record_pagination {
//     height: 6%;
//   }
// }
</style>
